<template>
  <div class="container">
    <p>{{ msg }}</p>
  </div>
  <div class="p-3 m-3 border rounded-3 shadow">
    <p>{{ bookMsg }}</p>
    <p>{{ now() }}</p>
    <p>{{ now2 }}</p>
  </div>
  <div class="p-3 m-3 border rounded-3 shadow">
    <p>可写计算属性</p>
    <p>
      <input type="text" v-model="familyName" placeholder="姓">
      <input type="text" v-model="givenName" placeholder="名">
      <span>{{ fullNameWrite }}</span>
    </p>
  </div>
  <div class="p-3 m-3 border rounded-3 shadow">
    <h4>计算属性获限上一个值</h4>
    <div class="row align-items-center">
      <div class="col-auto">
        <input type="text" class="form-control" v-model="familyName" placeholder="请输入姓">
      </div>
      <div class="col-auto">
        <input type="text" class="form-control" v-model="givenName" placeholder="请输入名">
      </div>
      <div class="col-auto">
        <span class="form-text">Now：{{ fullName }}</span>
      </div>
      <div class="col-auto">
        <span class="form-text">{{ prevFullName }}</span>
      </div>
      <div class="col-auto">

      </div>
    </div>


  </div>

</template>
<script setup lang="ts">
import {computed, reactive, type Ref, ref} from "vue";

const msg = computed(() => {
  return Math.random() > 0.5 ? "大于0.5" : "小于0.5";
});

const author = reactive({
  name: "刘慈欣",
  book: [
    '三体',
    '流浪地球',
  ],
});
//定义一个计属属性
const bookMsg = computed(() => {
  return author.book.length > 0 ? `${author.name}出版${author.book.length}本书` : `${author.name}没有出版过书`;
});
const now2 = computed(() => {
  return formatDate(new Date());
});
const familyName = ref("张");
const givenName = ref("三");
const prevFullName = ref('');
const fullName = computed((prev) => {
  prevFullName.value = (prev ? `Previous：${prev}` : '');
  return familyName.value + givenName.value;
})
//可写计算属性
const fullNameWrite = computed({
  get() {
    // 在 JavaScript ref定义的变量中需要.value
    return `${familyName.value}${givenName.value}`;
  },
  set(newName: Ref) {
    familyName.value = newName.value.substring(0, 1);
    givenName.value = newName.value.substring(1);
  }
});


const fullName2 = computed((prev) => {
  return `${familyName}${givenName}`;
})


function now() {
  return formatDate(new Date());
}

// 格式化函数
function formatDate(date: Date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const aa = ref(0);
</script>
